/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import util.Data_variante;
import util.Lucene_Index;
import util.user_info;

/**
 *
 * @author dragonboy
 */
public class CheckSession extends HttpServlet {
    protected String displayName;
    protected int userType;
    protected String bossOfUser;
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */    
    protected boolean CheckLogin_Lucene(String username, String passwd, String lastLogin) throws CorruptIndexException, IOException, ParseException{
        File file = new File(Data_variante.loginDB_file);
        FSDirectory dir = FSDirectory.open(file);
        Searcher searcher
            = new IndexSearcher(dir);
        QueryParser parser = new QueryParser(Version.LUCENE_34, "UserID", new StandardAnalyzer(Version.LUCENE_34));
        String command = "Username:"+username+" AND Passwd:"+passwd;
        Query myquery = parser.parse(command);
        
        TopDocs results = searcher.search(myquery,1);
        if(results.totalHits == 1){
            ScoreDoc[] hits = results.scoreDocs;
            int docid = hits[0].doc;
            Document doc = searcher.doc(docid);
            displayName = doc.get("Displayname");
            userType = Integer.valueOf(doc.get("Type"));
            bossOfUser = doc.get("Boss");
            searcher.close();
            Document newDoc = new Document();
            newDoc.add(new Field("UserID", doc.get("UserID"), Field.Store.YES, Field.Index.NOT_ANALYZED));
            newDoc.add(new Field("Username", doc.get("Username"),Field.Store.YES, Field.Index.NOT_ANALYZED));
            newDoc.add(new Field("Passwd", doc.get("Passwd"), Field.Store.YES, Field.Index.NOT_ANALYZED));
            newDoc.add(new Field("Displayname", displayName, Field.Store.YES, Field.Index.NOT_ANALYZED));
            newDoc.add(new Field("Type", doc.get("Type"), Field.Store.YES, Field.Index.NOT_ANALYZED));
            newDoc.add(new Field("LastLogin", lastLogin, Field.Store.YES, Field.Index.NOT_ANALYZED));
            newDoc.add(new Field("Boss", doc.get("Boss"), Field.Store.YES, Field.Index.ANALYZED));
            IndexWriter writer = new IndexWriter(dir, Lucene_Index.getAnalyzer(), IndexWriter.MaxFieldLength.LIMITED);
            writer.deleteDocuments(myquery);
            writer.addDocument(newDoc);
            writer.close();
            return true;
        }else{
            return false;
        }
    }
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, CorruptIndexException, ParseException {
        
        
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String lastLogin = dateFormat.format(date);
        Enumeration enumAttr =  request.getParameterNames();
        while(enumAttr.hasMoreElements()){
            String name = (String)enumAttr.nextElement();
            //System.out.println("name is: "+ name + " value is: "+ request.getParameter(name));
        }
        
        final long _duration = 1000*60*60*5 ;//5 hours
        Date expires = new Date(System.currentTimeMillis()+ _duration);
        
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        String  username = request.getParameter("username");
        //System.out.println("username: "+username);
        String  passwd = request.getParameter("password");
        //System.out.println("passwd: "+passwd);
        HttpSession session = request.getSession(false);
        if(session!= null){
            session.invalidate();
        }
        if(!CheckLogin_Lucene(username, passwd, lastLogin)){
            response.sendRedirect("../index.html");
        } else{
            session = request.getSession(true);
            session.setAttribute("username", username);
            session.setAttribute("displayName", displayName);
            session.setAttribute("userType", String.valueOf(userType));
            session.setAttribute("bossOfUser", bossOfUser);
            //session.setAttribute("passwd", passwd);
            //Cookie _cookie = new Cookie(username, passwd);
            response.sendRedirect("../servlet/Greeting");
        }
        
        /*try {
             TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet CheckSession</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet CheckSession at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             
        } finally {            
            out.close();
        }*/
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (CorruptIndexException ex) {
            Logger.getLogger(CheckSession.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(CheckSession.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (CorruptIndexException ex) {
            Logger.getLogger(CheckSession.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(CheckSession.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
